package com.ruoyi.common.core.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.ruoyi.common.core.utils.sql.SqlUtil;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableSupport;

import java.util.List;

/**
 * 分页工具类
 *
 * @author ruoyi
 */
public class PageUtils extends PageHelper
{
    /**
     * 设置请求分页数据
     */
    public static void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageMethod.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }
    /**
     * PageInfo 分页
     *
     * @param currentPage 当前页
     * @param pageSize    每页大小
     * @param list        所有list类型数据
     *
     * @return PageInfo<T>
     */
    public static <T> PageInfo<T> getFormDataPageInfo(Integer currentPage, Integer pageSize, List<T> list) {
        PageInfo<T> objectPageInfo = new PageInfo<>();
        // 总条数
        int size = list.size();
        objectPageInfo.setTotal(size);
        if (currentPage > 0 && pageSize > 0) {
            // 总页数
            objectPageInfo.setPages(size == 0 ? 0 : size % pageSize == 0 ? size / pageSize : size / pageSize + 1);
            // 截取的范围
            int index = (currentPage - 1) * pageSize;
            list = list.subList(index, (size - index > pageSize ? index + pageSize : size));
            // 当前页
            objectPageInfo.setPageNum(currentPage);
            //  每页数量
            objectPageInfo.setPageSize(pageSize);
        }
        // 当前页显示的数据
        objectPageInfo.setList(list);
        return objectPageInfo;
    }
    /**
     * @Description:转换为 IPage 对象
     * @Author: tarzan
     * @Date: 2019/10/31 9:40
     */
    public static <T, E> IPage<T> copy(IPage page, List<E> sourceList, Class<T> targetClazz) {
        IPage pageResult = new Page(page.getCurrent(),page.getSize(),page.getTotal());
        pageResult.setPages(page.getPages());
        //List<T> records = BeanUtils.copy(sourceList, targetClazz);
        //pageResult.setRecords(records);
        return pageResult;
    }

    /**
     * @Description:转换为 IPage 对象
     * @Author: tarzan
     * @Date: 2019/10/31 9:40
     */
    public static <T, E> IPage<T> copy(IPage page, Class<T> targetClazz) {
        return copy(page,page.getRecords(),targetClazz);
    }
    /**
     * 清理分页的线程变量
     */
    public static void clearPage()
    {
        PageMethod.clearPage();
    }
}
